package com.zjsru.controller;

import com.zjsru.pojo.Result;
import com.zjsru.pojo.User;
import com.zjsru.service.UserService;
import com.zjsru.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //用户注册
    @PostMapping("/user/public/register")
    public Result register(@RequestParam String username, @RequestParam String password) {
        if (username == null || password == null) {
            return Result.error(500, "用户名或密码不能为空");
        }
//        检测用户名是否重复
        if (userService.queryUserByUsername(username) != null) {
            return Result.error(500, "用户名已存在");
        }
        userService.register(username, password);
        return Result.success("注册成功");
    }

    //用户登录
    @GetMapping("/user/public/login")
    public Result checkLogin(@RequestParam String username, @RequestParam String password) {
        if (username == null || password == null) {
            return Result.error(500, "用户名或密码不能为空");
        }
        User user = userService.checkLogin(username, password);

        if (user != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("user_id", user.getUser_Id());

            log.info("用户名:{},密码:{}", username, password);


            String jwt = JwtUtils.generateJwt(claims);
            log.info("jwt:{}", jwt);
            return Result.success(jwt);
        }else{
            return Result.error(500, "用户名或密码错误");
        }
    }


    //查询用户信息
    @GetMapping("/user/query/{user_Id}")
    public Result queryUserById(@PathVariable("user_Id") Long user_Id) {
        try{
            User user = userService.queryUserById(user_Id);
            return Result.success(user);
        }
        catch (Exception e){
            return Result.error(500, "查询失败:"+e.getMessage());
        }
    }
    // 更新用户信息
    @PutMapping("/user/update")
    public Result updateUser(@RequestBody User user) {
        try {
            if (user.getUser_Id() == null) {
                return Result.error(500, "用户ID不能为空");
            }
            userService.updateUser(user);
            return Result.success("用户信息更新成功");
        } catch (Exception e) {
            return Result.error(500, "更新失败：" + e.getMessage());
        }
    }
    //验证用户状态为0或1
    @GetMapping("/user/check-status")
    public boolean checkStatus(@RequestParam String username) {
        User user = userService.queryUserByUsername(username);
        if (user == null) {
            return false;
        }
        return user.getStatus() == 0;
    }
}
